package com.heima.article.listener;

import com.alibaba.fastjson.JSON;
import com.heima.article.service.ApArticleService;
import freemarker.template.TemplateException;
import org.apache.kafka.clients.consumer.Consumer;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.Map;

@Component
public class Listener {

    @Autowired
    private ApArticleService apArticleService;

    /**
     * 监听上下架文章
     * @param consumerRecord
     * @param consumer
     */
    @KafkaListener(topics = "down_or_up-topic")
    public void listenerDownOrUp(ConsumerRecord<String,String> consumerRecord, Consumer<String,String> consumer) throws TemplateException, IOException {
        if (!StringUtils.isEmpty(consumer)){
            apArticleService.downOrUp(JSON.parseObject(consumerRecord.value(),Map.class));
        }
        try {
            consumer.commitAsync();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                consumer.commitSync();
            } finally {
                consumer.close();
            }
        }
    }
}
